package com.bawei.splash

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ValueAnimator
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.animation.LinearInterpolator
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.cache.CacheManager
import com.bawei.cache.CacheStrategy
import com.bawei.common.RoutePath
import com.bawei.splash.databinding.ActivitySplashBinding

class SplashActivity : AppCompatActivity() {

    private var mValue: Int = 0

    private val mDataBinding: ActivitySplashBinding by lazy {
        ActivitySplashBinding.inflate(LayoutInflater.from(this))
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //是否属于第一启动（安装后第一次启动）
        var isFirst = CacheManager.getCache(CacheStrategy.MMKV).getBool("isFirst")
        if(!isFirst){
            CacheManager.getCache(CacheStrategy.MMKV).putBool("isFirst", true)
            setContentView(mDataBinding.root)
            //立即进入按钮点击事件
            mDataBinding.tvJustGo.setOnClickListener {
                ARouter.getInstance().build(RoutePath.PATH_MAIN).navigation()
                this@SplashActivity.finish()
            }
            //启动倒计时动画
            startTimer()
        } else {
            ARouter.getInstance().build(RoutePath.PATH_MAIN).navigation()
            this@SplashActivity.finish()
        }
    }

    private fun startTimer() {
        var valueAnimator = ValueAnimator.ofInt(5, 0)
        valueAnimator.duration = 5000
        valueAnimator.interpolator = LinearInterpolator()

        //设置更新监听
        valueAnimator.addUpdateListener { animation ->
            var index = animation.animatedValue as Int
            if (index != mValue) {
                mValue = index
                mDataBinding.tvTimer.text = "${mValue}秒"
            }
        }

        //设置动画结束监听
        valueAnimator.addListener(object : AnimatorListenerAdapter() {
            override fun onAnimationEnd(animation: Animator) {
                mDataBinding.tvTimer.postDelayed({
                    ARouter.getInstance().build(RoutePath.PATH_MAIN).navigation()
                }, 200)
            }
        })
        valueAnimator.start()
    }
}